#!/usr/bin/python
#
# GPL v2
#
# Authors:
#   Martijn Brekhof <m.brekhof@gmail.com>
#

import socket
import re
from datetime import datetime

HOST=''
PORT=2300
wakeup_list = [] 

def gen_wakeupcall(data):
	data_split = data.split("::", 4)
	date = datetime.strptime(data_split[2], "%Y-%m-%d %H:%M")
	return (addr[0], date, data_split[3])

def handle_data(data):
	if re.match("::del::[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]::[A-Za-z0-9][A-Za-z0-9]*", data):
		try:
			wakeup_list.remove(gen_wakeupcall(data))
		except ValueError:
			pass
	if re.match("::add::[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]::[A-Za-z0-9][A-Za-z0-9]*", data):
		wakeup_list.append(gen_wakeupcall(data)) 

def wakeuphost(data):
	s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

	# replace '\x00\x1A\x92\x9D\x69\x85' with the MAC address
	s.sendto('\xff'*6+'\x00\x1A\x92\x9D\x69\x85'*16, ('<broadcast>', 7))

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while 1:
	conn, addr = s.accept()
	print 'Connected by', addr
	while 1:
		data = conn.recv(1024)
		if not data: break
		handle_data(data)
	conn.send(data)
	print wakeup_list
conn.close


